# coding:utf-8
# author:WHY
# time:2016-05-22

from scanner import Scanner
import sys
import argparse

parser = argparse.ArgumentParser(
    description='This tool is a lexical made by WHY')
parser.add_argument('-g', action="store", nargs = '?', dest='gra', required=True,
    help='The grammar file path')
parser.add_argument('-s', action="store", nargs = '?', dest='src', required=True,
    help='The source file path')
parser.add_argument('-o', action="store", nargs = '?', dest='out', default='lexical.out',
    help='The output file path')
args = parser.parse_args()
args = vars(args)


grammar = []
srcFile = open(args['src'], 'r')
src = srcFile.read()

scan = Scanner(src, 'begin')

fileInput = open(args['gra'], 'r')
for line in fileInput.readlines():
	if line[-1] == '\n':
		line = line[0:-1]
	if len(line) == 0:
		continue
	if line[0] == '@':
		if len(grammar) != 0:
			scan.makeNFA(grammar, name)
		name = line
		grammar = []
	if line == '@keyword':
		break;
	else:
		arr = line.split(' ')
		line = tuple(arr)
		grammar.append(line)
fileInput.close()
name = ''
grammar = []
fileInput = open(args['gra'], 'r')
for line in fileInput.readlines():
	if line[-1] == '\n':
		line = line[:-1]
	if line == '@type':
		break
	if line == '@keyword':
		name = 'keyword'
	elif name == 'keyword':
		grammar.append(line)
fileInput.close()
scan.addKeyword(grammar)
name = ''
grammar = []
fileInput = open(args['gra'], 'r')
for line in fileInput.readlines():
	if line[-1] == '\n':
		line = line[:-1]
	if line == '@type':
		name = 'type'
	elif name == 'type':
		grammar.append(line)
scan.addType(grammar)
fileInput.close()

scan.NFAtoDFA()

fileOutput = open(args['out'], 'w')

while scan.getState() != 'EOF':
	token = scan.getToken()
	tokenType = scan.getTokenType()
	if tokenType != 'EOF' and tokenType != '@comment':
		fileOutput.write("%s %d:%d\t%s\t%s\n" % (args['src'], scan.getRow(), scan.getCol(), tokenType, token,))

fileOutput.close()